//using ScenicAreas.ILog;
//using ScenicAreas.Log;
using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Threading;
namespace Lcygcc.Infrastructure.WindowService
{
	public class ServiceDaemon
	{
		private WindowsService service;
//		private ILogFactory iLogFactory;
		private bool isStart;
		public ServiceDaemon()
		{
//			this.iLogFactory = new LogFactory();
		}
		public void Start(WindowsService service)
		{
			if (this.isStart)
			{
				return;
			}
			this.isStart = true;
			this.service = service;
			new Thread(new ThreadStart(this.CheckServiceHost))
			{
				IsBackground = true
			}.Start();
		}
		public void Stop()
		{
		}
		private void CheckServiceHost()
		{
			Thread.Sleep(5000);
			ServiceController serviceController = ServiceController.GetServices().ToList<ServiceController>().Find((ServiceController x) => x.DisplayName.ToLower() == this.service.Name.ToLower());
			if (serviceController == null)
			{
				return;
			}
			while (true)
			{
//				ILogger logger = this.iLogFactory.CreateLogger("windows服务守护");
				try
				{
					serviceController.Refresh();
					if (serviceController.Status != ServiceControllerStatus.Running && serviceController.Status != ServiceControllerStatus.StartPending)
					{
						if (serviceController.Status != ServiceControllerStatus.Stopped && serviceController.Status != ServiceControllerStatus.StopPending)
						{
//							logger.Info("服务状态", string.Format("{0}状态：{1}", this.service.ProcessName, serviceController.Status.ToString()));
							serviceController.Stop();
						}
						else
						{
							string processName = this.service.ProcessName;
							Process[] processesByName = Process.GetProcessesByName(processName);
							if (processesByName.Length > 0)
							{
//								logger.Info("进程重启", string.Format("{0}重启。。。。", this.service.ProcessName));
								processesByName[0].Kill();
							}
							serviceController.Start();
						}
					}
				}
				catch (Exception ex)
				{
//					logger.Error("服务重启", "重启xmpp服务异常", ex);
				}
				finally
				{
//					logger.Complete();
				}
				Thread.Sleep(8000);
			}
		}
	}
}
